#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    struct Less{
        bool operator()(pair<string, int>first, pair<string, int>second){
            if(first.second < second.second){
                return true;
            }
            if(first.second == second.second && first.first > second.first){
                return true;
            }
            return false;
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> m;
        for(string& val : words){
            m[val]++;
        }
        priority_queue<pair<string, int>, vector<pair<string, int>>, Less> maxHeap(m.begin(), m.end());
        vector<string>ret;
        while(k--){
            ret.push_back(maxHeap.top().first);
            maxHeap.pop();
        }
        return ret;
    }
};